package com.fh.fruit.service.goods.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import com.fh.dao.DaoSupport;
import com.fh.entity.Page;
import com.fh.fruit.entity.goods.Goods;
import com.fh.fruit.entity.goods.GoodsUnit;
import com.fh.fruit.entity.label.Label;
import com.fh.fruit.entity.label.LabelAttr;
import com.fh.fruit.entity.spec.Spec;
import com.fh.fruit.service.goods.GoodsManager;
import com.fh.fruit.util.DateUtil;
import com.fh.util.PageData;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 * 商品 修改时间：2017.9.20
 */
@Service("goodsService")
public class GoodsService implements GoodsManager {

	@Resource(name = "sqlSessionFactory")
	private SqlSessionFactory factory;

	@Resource(name = "daoSupport")
	private DaoSupport dao;
	
	@Value("${IMAGE_BASE_URL}")
	private String IMAGE_BASE_URL;

	@Override
	public String getClassIdByPid(String id) throws Exception {
		return (String) dao.findForObject("GoodsMapper.getClassIdByPid", id);
	}

	@Override
	@SuppressWarnings("unchecked")
	public List<Goods> listGoods(Page page) throws Exception {
		return (List<Goods>) dao.findForList("GoodsMapper.goodslistPage", page);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<GoodsUnit> getGoodsUnitList() throws Exception {
		return (List<GoodsUnit>)dao.findForList("GoodsMapper.getGoodsUnitList");
	}

	@Override
	public int deleteImage(Map<Object, String> param) throws Exception {
		return (int)dao.delete("GoodsMapper.deleteImage", param);
	}
	
	@Override
	public int saveG(PageData pd) throws Exception {
		int num=1;
		try {
			num=(int)dao.findForObject("GoodsMapper.getGoodsNum", pd);
			if(num >0){
				num=2;
				return num;
			}
			dao.save("GoodsMapper.saveG", pd);
			String goodsId = (String) dao.findForObject("GoodsMapper.getGoodsById", "1");
			if(goodsId == null){
				num=0;
				return num;
			}
			pd.put("goodsId", goodsId);
			String attr=(String)pd.get("attr");
			if(attr != null && !"".equals(attr)){
			JSONArray json = JSONArray.fromObject(attr); 
			Label label = new Label();
			LabelAttr la = new LabelAttr();
			label.setGoodsId(Integer.parseInt(goodsId));
			la.setGoodsId(Integer.parseInt(goodsId));
				if(json.size()>0){
					Map<String,Integer> map=new HashMap<>();
					  for(int i=0;i<json.size();i++){
						   JSONObject job = json.getJSONObject(i); 
						   String key=(String)job.get("key");
						   label.setLabelName(key);
						   dao.save("GoodsMapper.saveGoodsLabel", label);
						   JSONArray val= job.getJSONArray("value");
						   if(val.size()>0){
							   for(int y=0;y<val.size();y++){
								  la.setLabelName(label.getLabelName());
								  la.setAttrName(val.getString(y));
								  la.setLabelId(label.getId());
								  la.setSerial("p"+(y+1));
								  dao.save("GoodsMapper.saveGoodsLabelAttr",la);
								  map.put(i+"-"+la.getSerial(), la.getId());
							   }
						   }
					  }
					  
						String param=(String)pd.get("param");
						if(param != null && !"".equals(param)){
							JSONArray js = JSONArray.fromObject(param); 
							if(js.size()>0){
								for(int i=0;i<js.size();i++){
									JSONObject job = js.getJSONObject(i); 
									JSONArray val= job.getJSONArray("value");
									if(val.size()>0){
									   for(int y=0;y<val.size();y++){
										  JSONArray va= val.getJSONArray(y);
										 pd.put("stock", va.getString(0));
										 String attrs= va.getString(1);
										 pd.put("spec", returnAttrIds(attrs,map));
										 String classId= pd.getString("classId");
										 pd.put("code", "p"+classId+goodsId);
										 dao.save("GoodsMapper.saveGoodsSpec", pd);
										 String specId = (String) dao.findForObject("GoodsMapper.getSpecById", "1");
										 if(specId == null){
											 num=0;
											 return num;
										 }
										 pd.put("specId", specId);
										 pd.put("code", "p"+classId+goodsId+specId);
										 num=(int)dao.update("GoodsMapper.updateSpec", pd);
										 if(num ==0){
											 return num;
										 }
									   }
									}
								}
							}
						} 
					  
				}
			}else{
				String classId= pd.getString("classId");
				 pd.put("code", "p"+classId+goodsId);
				dao.save("GoodsMapper.saveGoodsSpec1", pd);
				String specId = (String) dao.findForObject("GoodsMapper.getSpecById", "1");
				 if(specId == null){
					 num=0;
					 return num;
				 }
				 pd.put("specId", specId);
				 pd.put("code", "p"+classId+goodsId+specId);
				 num=(int)dao.update("GoodsMapper.updateSpec", pd);
				 if(num ==0){
					 return num;
				 }
			}
		
		} catch (Exception e) {
			e.printStackTrace();
			num=0;
			return num;
		}finally {
			if(num!=1){
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			}
		}
		return num;
	}

	
	public String returnAttrIds(String attrs,Map<String, Integer> map){
		String attrArray[] = attrs.split("-");
		StringBuffer sb = new StringBuffer();
		for(int i = 0;i<attrArray.length; i++){
			sb.append(map.get(i+"-"+attrArray[i]));
			if(i != attrArray.length-1){
				sb.append("-");
			}
		}
		return sb.toString();
	}
	
	@Override
	public Goods findById(PageData pd) throws Exception {
		return (Goods)dao.findForObject("GoodsMapper.findById", pd);
	}

	@Override
	public void editG(PageData pd) throws Exception {
		dao.update("GoodsMapper.updateGoods", pd);
	}

	@Override
	public void delGood(PageData pd) throws Exception {
		dao.delete("GoodsMapper.delGood", pd);
	}

	@Override
	public void delGoods(PageData pd) throws Exception {
		dao.delete("GoodsMapper.delGoods", pd);
	}

	@Override
	public int updateState(PageData pd) throws Exception {
		return (int)dao.update("GoodsMapper.updateState", pd);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Spec> getGoodsSpecList(Page page) throws Exception {
		return (List<Spec>)dao.findForList("GoodsMapper.getGoodsSpeclistPage", page);
	}

	@Override
	public LabelAttr getLabelAttr(String id) throws Exception {
		return (LabelAttr)dao.findForObject("GoodsMapper.getLabelAttr", id);
	}

	@Override
	public Spec getGoodsSpec(PageData pd) throws Exception {
		return (Spec)dao.findForObject("GoodsMapper.getGoodsSpec", pd);
	}

	@Override
	public void updateGoodsEdit(PageData pd) throws Exception {
		dao.update("GoodsMapper.updateGoodsEdit", pd);
	}

	@Override
	public int updateSpecState(PageData pd) throws Exception {
		return (int)dao.update("GoodsMapper.updateSpecState", pd);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Label> getGoodsLabelList(PageData pd) throws Exception {
		return (List<Label>)dao.findForList("GoodsMapper.getGoodsLabelList", pd);
	}

	@Override
	public int updateBatchState(PageData p) throws Exception {
		return (int) dao.update("GoodsMapper.updateBatchState", p);
	}

	@Override
	public int updateSpecStateList(PageData p) throws Exception {
		return (int) dao.update("GoodsMapper.updateSpecStateList", p);
	}

	@Override
	public int updateGoodsState(Goods data) throws Exception {
		return (int) dao.update("GoodsMapper.updateGoodsState", data);
	}

	@Override
	public void updateSpecStates(Spec spec) throws Exception {
		dao.update("GoodsMapper.updateSpecStates", spec);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<GoodsUnit> getHarvestUnitList() throws Exception {
		return (List<GoodsUnit>)dao.findForList("GoodsMapper.getHarvestUnitList");
	}

	@SuppressWarnings("unchecked")
	@Override
	public Map<String, Object> getGoodsSpecTime(PageData pd) throws Exception {
		return (Map<String,Object>)dao.findForObject("GoodsMapper.getGoodsSpecTime", pd);
	}

	@Override
	public int updateImage(Map<Object, String> param) throws Exception {
		return (int)dao.update("GoodsMapper.updateImage", param);
	}

	@Override
	public int updateSpecImage(Map<Object, String> param) throws Exception {
		return (int)dao.update("GoodsMapper.updateSpecImage", param);
	}
}
